// 首页
// 获取应用实例
const app = getApp()
var basePage = require('../../../common/BasePage');
Page({
    behaviors: [basePage],
    data: {
        /**首页不检查用户信息 */
        showGroup: false,
        checkMobile: false,
        video: '', //视频地址，是否播放视频
        wh_id: 1, //当前仓库id
        product_id: 0, //当前选中得产品id
        sku: 1, //可以加入购物车得最大数量
        nums: 1, //购买产品数量
        addCart: false, //是否显示添加购物车弹窗
        /**加入购物车产品名称 */
        product_name: '',
        /**自荐品牌榜 */
        brandPdcs: [],
        bannerArr: [],
        swiperCurrent: 0,
        /**通告列表 */
        declareArr: [],
        /**选中的城市索引 */
        tabIndex: 0,
        // articleArr: [], //头条通告列表
        /**供应商列表 */
        supplierArr: [],
        /**分类索引 */
        catIndex: 0,
        /**分类数据 */
        catArr: [
            // {
            //   loading: false,
            //   title: '全部',
            //   current_page: 0,
            //   pages: 1,
            //   data: [],
            //   reqData: {
            //     type:0
            //   }
            // },
            // {
            // 	loading: false,
            // 	title: '促销',
            // 	current_page: 0,
            // 	pages: 1,
            // 	data: [],
            // 	reqData: {
            // 		type: 3
            // 	}
            // },
            // {
            // 	loading: false,
            // 	title: '天天特价',
            // 	current_page: 0,
            // 	pages: 1,
            // 	data: [],
            // 	reqData: {
            // 		type: 2
            // 	}
            // },
            {
                loading: false,
                title: '采购推荐',
                current_page: 0,
                pages: 1,
                data: [],
                url: "/home/supplier/product/index?limit=20",
                reqData: {
                    purchase: 1,
                    limit: 20
                }
            },
            {
                loading: false,
                title: '整点秒杀',
                current_page: 0,
                pages: 1,
                url: "/home/ump/seckill/product?limit=20",
                data: [],

            }
        ],
        activeIndex: 0,
        activeArr: [
            // {
            //     title:"秒杀",
            //     subtitle:"性价比高",
            //     url:""
            // },
            {
                title: "活动",
                subtitle: "今日活动",
                url: ""
            },
            {
                title: "推荐",
                subtitle: "优品严选",
                url: ""
            },
            {
                title: "秒杀",
                subtitle: "性价比高",
                url: ""
            },
            // {
            //     title:"活动",
            //     subtitle:"今日活动",
            //     url:""
            // },
            {
                title: "视频",
                subtitle: "实物购买",
                url: ""
            }
        ],
        /**金刚区导航 2021.12.31 */
        navSwiperIndex: 0,
        navListAll2: [{
                navList: [{
                    linkType: 'switchTab',
                    icon: "../../../assets/newIndex/tab1.png",
                    imgText: "体",
                    text: "联系客服",
                    url: 'kf'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab2.png",
                    imgText: "体",
                    text: "鲜花图册",
                    url: '/pages/album/album?state=1'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab3.png",
                    imgText: "体",
                    text: "常购清单",
                    url: '/pages/cls/often/List'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab4.png",
                    imgText: "体",
                    text: "包装费",
                    url: '/pages/article/Index?article_id=13'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab5.png",
                    imgText: "体",
                    text: "交易须知",
                    url: '/pages/article/help_center/help_center?cate_id=3&title=交易须知&wh_id=1'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab6.png",
                    imgText: "体",
                    text: "同城鲜花",
                    url: '/pages/chat/cityGroup/index'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab7.png",
                    imgText: "体",
                    text: "当日账单",
                    url: '/pages/article/Index?article_id=24'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab8.png",
                    imgText: "体",
                    text: "运费查询",
                    url: '/pages/logistics/freight/freight'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab9.png",
                    imgText: "体",
                    text: "每日花价",
                    url: '/pages/cls/price/List'
                }, {
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab10.png",
                    imgText: "体",
                    text: "帮助中心",
                    url: '/pages/article/help_center/help_center?cate_id=4'
                }]
            },
            {
                navList: [{
                    linkType: 'navigateTo',
                    icon: "../../../assets/newIndex/tab11.png",
                    imgText: "体",
                    text: "求购",
                    url: '/pages/cls/qiugou_edit/edit'
                }]
            }
        ],
        areaData: [{
            wh_id: 1, //仓库id
            title: '昆明总站',
            nav: [], //金刚区导航栏
        }],
        /**不包含昆明总仓的 数组 */
        areaArr: [],
        search: '',
        tabsLoading: false,
        totalMsg: 0,
        uid: "",
        showSubscribeClick: false,
        radioSale: -1,
        checkedSale: false,
        special: [{
                title: "天天特价",
                url: '/home/supplier/product/index',
                data: {
                    type: 2
                }
            },
            // {
            // 	title:"秒杀专区",
            // 	url:'/home/ump/seckill/product',
            // 	data:{}
            // }
        ],
        specialloading: true,
        specialList: [], //天天特价
        videoList: [], //视频商品
        sortList: [],
        specialIndex: 0,
        //预售
        bookPdc: "",
        booknums: 1,
        booksku: 1,
        //分类
        sortFlowerList: [],
        current_page: 0,
        pages: 1,
        sortIndex: 0, //分类角标
        sortFlowerloading: true,
        //秒杀
        pdc: {},
        time: "",
        showMoreArea: false,
        navHeight: 0,
        navInfo: getApp().globalData.navInfo,
        //整点秒杀
        seckillList: [],
        seckillloading: true,
        videoloading: true,
        analysisList: [],
        turnoverList: [],
        sales: 0, //今日成交量
        marketState: "",
        startTime: "",
        endTime: "",
        warehouse: null, //当前仓库信息
        showCount: false,
        timeCount: 0,
        timeData: {},

    },
    moreArea() {
        this.setData({
            showMoreArea: true
        })
    },
    toCatList() {
        wx.switchTab({
            url: "/pages/cat/Index",

        })
    },

    toAnalysis(e) {
        console.log("数据分析", e)
        var cate_id = ""
        if (e.currentTarget.dataset.item) {
            cate_id = e.currentTarget.dataset.item.cate_id
        }
        wx.navigateTo({
            // url: "/pages/cls/market/Echart" ,
            url: "/pages/cls/index/analysis/analysis?wh_id=" + this.data.wh_id + "&cate_id=" + cate_id,
        })
    },
    tolink(e) {
        let link = e.currentTarget.dataset.link
        if (link) {
            wx.navigateTo({
                url: link,
            })
        }
    },
    onSwiperChange(e) {
        this.data.headBgTransition || this.setData({
            headBgTransition: true
        });
        const {
            current
        } = e.detail;
        this.setData({
            swiperCurrent: current
        });
    },
    nav_click(e) {
        // console.log(e.currentTarget.dataset);
        let nav = e.currentTarget.dataset.nav
        if (nav.url == 'kf') {
            return this.service_click()
        }
        if (nav.linkType == 'func') {
            return this[nav.url]();
        }
        if (nav.linkType == 'toList') {
            return this.toList(e);
        }
        if (nav.linkType == 'switchTab') {
            return wx.switchTab({
                url: nav.url,

            })
        }
        if (nav.linkType == 'sort') {
            wx.setStorageSync('catId', nav.id)
            return wx.switchTab({
                url: nav.url,

            })
        }
        if (nav.linkType == 'url') {
            return wx.navigateTo({
                url: nav.url,
            })
        }
        wx.navigateTo({
            url: nav.url + '?wh_id=' + this.data.wh_id,
        })
    },
    /**
     * 点击客服按钮
     */
    service_click() {
        // console.log("socket连接状态", getApp().globalData.showSocket)
        var that = this
        if (!getApp().globalData.showSocket) {
            wx.showModal({
                title: '客服系统已断开',
                content: '请确定是否重连',
                success(res) {
                    if (res.confirm) {
                        // console.log('用户点击确定')
                        getApp().globalData.number = 0
                        getApp().globalData.againSocket = 1
                        // getApp().connectSocket();
                        that.getUserInfo()

                    } else if (res.cancel) {
                        // console.log('用户点击取消')
                    }
                }
            })
            return;
        }
        // console.log("聊天次数", getApp().globalData.number)
        if (getApp().globalData.number >= 3) {
            wx.showToast({
                title: '聊天服务异常，请重启小程序或者联系客服',
                icon: 'none',
                duration: 2000
            })
            return;
        }
        let warehouse = getApp().globalData.warehouse;
        // this.setData({
        // 	totalMsg: 0
        // })
        // wx.navigateTo({
        //   url: '/pages/album/contact_service/contact?mobile='+warehouse.service_phone+"&face="+warehouse.service_qrcode,
        // })
        wx.navigateTo({
            url: '/pages/chat/chatList/chatList'
        })
    },
    /**下拉刷新 */
    onPullDownRefresh() {
        let catIndex = this.data.catIndex;
        this.data.catArr[catIndex].current_page = 0;
        this.req_cat_data(catIndex)
    },
    /**触底加载下一页 */
    onReachBottom() {
        // this.getFlowers()
        // this.req_cat_data(this.data.catIndex)
    },
    onLoad(opt) {
        console.log("首页", opt)
        setTimeout(() => {
            this.setData({
                showGroup: true
            })
        }, 500)
        if (opt.uid) {
            this.setData({
                uid: opt.uid
            })
        }
        if (opt.scene) {
            var scene = opt.scene
            var i = scene.lastIndexOf("invite_id%3D")
            var uid = scene.substring(i + 12, scene.length);
            console.log("首页uid", uid)
            this.setData({
                uid: uid
            })
        }

        // this.getMyfriend()
        this.getStatistics() //统计用户访问量
        this.getNav() //获取首页导航
        this.getwarehouse() //获取仓库信息

    },
    //获取仓库信息
    getwarehouse() {
        //请求仓库信息(队列请求)请求仓库之后，接着请求轮播图
        this.request({
            url: this.data.host + '/home/index/warehouse?limit=100'
        }, res => {
            // console.log("warehouse", res);
            let areaArr = [];
            for (let i = 1; i < res.data.length; i++) {
                areaArr.push(res.data[i]);
            }
            this.setData({
                areaData: res.data,
                areaArr
            });

            // console.log("areaData", this.data.areaData);
            if (res.data.length) {
                this.data.wh_id = res.data[0].wh_id;
                for (let i = 0; i < res.data.length; i++) {
                    res.data[i].index = i;
                }
                getApp().globalData.warehouse = res.data[0];
                getApp().globalData.areaData = res.data;
                this.setData({
                    warehouse: res.data[0]
                })
            }


        }, null, this.req_banner);
    },
    getNav() {
        this.request({
            url: this.data.host + "/home/index/nav"
        }, res => {
            //navListAll2
            var list = []
            var navListAll2 = this.data.navListAll2
            if (navListAll2.length >= 3) return
            res.data.map((val, index) => {
                if (index < 9) {
                    list.push({
                        linkType: 'sort',
                        icon: this.get_thumb(val.icon),
                        text: val.title,
                        url: '/pages/cat/Index',
                        id: val.link
                    })
                }
            })
            list.push({
                linkType: 'switchTab',
                icon: "../../../assets/newIndex/indexNav.png",
                text: "交易大厅",
                url: '/pages/cat/Index'
            })

            navListAll2.unshift({
                navList: list
            })
            // console.log("navListAll2",navListAll2)
            this.setData({
                navListAll2: navListAll2
            })
        })
    },
    onShow() {

        this.getSales()

        if (this.data.warehouse) {
            getApp().globalData.warehouse = this.data.warehouse
        }

        if (this.data.time && this.data.wh_id == 1) {
            this.getTimeSessions()
        }
        getApp().globalData.onMessage = this.onMessage;
        this.setData({
            totalMsg: getApp().globalData.msgCount
        })
        // console.log("替换监听方法")

        let Authorization = wx.getStorageSync('Authorization');
        if (getApp().globalData.SocketTask) { //如果未登陆或者已经链接socket  !Authorization || 
            return;
        }
        this.getUserInfo()



        // this.setData({
        // 	totalMsg:getApp().globalData.total_msg||0
        // })
    },
    getUserInfo() {
        this.request({
            url: this.data.host + "/home/user/info"
        }, res => {
            // console.log("user/info",res.data);
            let userInfo = getApp().globalData.userInfo = res.data;
            getApp().connectSocket();
        });
    },
    login_reload() {
        this.getUserInfo()

        this.getStatistics() //统计用户访问量
        this.getNav() //获取首页导航
        this.getwarehouse() //获取仓库信息

        this.getSales() //获取实时成交量

        // if (!this.data.userInfo.uid) {
        // 	this.request({
        // 		url: this.data.host + "/home/user/info"
        // 	}, res => {
        // 		// console.log("user/info",res.data);
        // 		let userInfo = getApp().globalData.userInfo = res.data;
        // 		getApp().connectSocket();
        // 	});
        // } else {
        // 	getApp().connectSocket();
        // }
    },
    //计算当前时间场次
    onChangeTime(e) {
        this.setData({
            timeData: e.detail,
        });
    },
    getTimeSessions() {

        var myDate = new Date(); //实例一个时间对象； 
        var y = myDate.getFullYear(); //获取系统的年； 
        var m = myDate.getMonth() + 1; //获取系统月份，由于月份是从0开始计算，所以要加1 
        var d = myDate.getDate(); // 获取系统日， 
        var h = myDate.getHours(); //获取系统时， 
        var min = myDate.getMinutes(); //分 

        var fs = y + "/" + m + "/" + d + " " + this.data.time.flower_stime
        fs = new Date(fs).getTime()
        var fl = y + "/" + m + "/" + d + " " + this.data.time.flower_ltime
        fl = new Date(fl).getTime()

        var time = new Date().getTime()
        var numTime = Number(this.data.time.stop_trade) * 60 * 1000
        var marketState = ""
        var startTime = "" //交易时间
        var endTime = "" //休市时间
        // console.log("时间",numTime)
        if (time < fs) {
            // console.log("休市")
            marketState = "休市"
            endTime = "00:00" + "~" + this.data.time.flower_stime
        } else if (time >= fs && time < fl) {
            // console.log("第一场交易中")
            marketState = "第一场交易中"
            startTime = this.data.time.flower_stime + "~" + this.data.time.flower_ltime
            var timeCount = new Date(fl).getTime() - new Date().getTime()
            this.setData({
                showCount: true,
                timeCount: timeCount
            })
            if(timeCount>0){
                setTimeout(()=>{
                    this.getTimeSessions()//倒计时结束重新计算交易场次
                },timeCount)
            }
            
        } else if (time > fl && (time < fl + numTime)) {
            // console.log("休市2")
            marketState = "休市"
            var time = new Date(fl + numTime);
            var hours = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
            var mm = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
            endTime = this.data.time.flower_ltime + "~" + hours + ":" + mm
        } else if (time > fl + numTime) {
            // console.log("第二次交易中")
            marketState = "第二场交易中"

            var time = new Date(fl + numTime);
            var hours = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
            var mm = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
            startTime = hours + ":" + mm + "~" + "00:00"
            //  距离结束时间的倒计时 第二场结束时间为0点
            var date = new Date();
            date.setHours(23, 59, 59);
            var timeCount = date.getTime() - new Date().getTime()
            if(timeCount>0){
                setTimeout(()=>{
                    this.getTimeSessions()//倒计时结束重新计算交易场次
                },timeCount)
            }
            this.setData({
                showCount: true,
                timeCount: timeCount
            })

        }
        console.log("marketState", marketState)
        this.setData({
            marketState: marketState,
            startTime: startTime,
            endTime: endTime
        })
    },
    //统计用户访问量
    getStatistics() {
        this.request({
            url: this.data.host + "/home/index/view"
        }, res => {})
    },
    nav_swiper_change(e) {
        this.setData({
            navSwiperIndex: e.detail.current
        })
    },
    //查询系统配置（秒杀时间）
    getTime() {
        this.request({
            url: this.data.host + '/home/index/config',
            data: {
                wh_id: this.data.wh_id,
                type: 2
            }
        }, res => {
            this.setData({
                time: res.data
            })
            if (this.data.wh_id == 1) {
                this.getTimeSessions()
            }

        });
    },

    onMessage(msg) {
        // console.log("聊天列表", msg)
        var that = this
        if (msg.type == "total_msg") {
            var totalMsg = msg.total_count
            that.setData({
                totalMsg: totalMsg
            })
        } else if (msg.type == "friend") {
            var totalMsg = this.data.totalMsg
            totalMsg = totalMsg + 1
            that.setData({
                totalMsg: totalMsg
            })
        }
    },
    //查询分类
    getNewSort() {
        this.request({
            url: this.data.host + "/home/product/indexCate",
            data: {
                wh_id: this.data.wh_id
            }
        }, res => {
            let list = res.data
            list.unshift({
                title: "全部",
                cate_id: ""
            })
            this.setData({
                sortList: list
            })
            this.getFlowers()
        })
    },
    //切换分类
    sort_change(e) {
        // console.log("e", e)
        this.setData({
            sortFlowerloading: true,
            sortIndex: e.detail.index,
            // current_page:0,
            // pages:1,
            // sortFlowerList:[]
        })
        this.getFlowers()
    },
    getFlowers() {

        var sortList = this.data.sortList
        // if (this.data.current_page == this.data.pages) {
        // 	return console.log("没有更多了");
        // }

        this.request({
            url: this.data.host + "/home/supplier/product/index",
            data: {
                limit: 10,
                wh_id: this.data.wh_id,
                cate_id: sortList[this.data.sortIndex].cate_id,
                // page: (this.data.current_page * 1) + 1,
            }
        }, res => {
            res.data.map(val => {
                val.thumb = this.get_thumb(val.product_img);
                // console.log("val.thumb",val.thumb);
            });
            // res.current_page == 1 ? list = res.data : list = list.concat(res.data);
            this.setData({
                sortFlowerList: res.data,
                sortFlowerloading: false
                // current_page:res.current_page,
                // pages:res.pages
            })
        })
    },


    getMyfriend() {
        this.request({
            url: this.data.host + "/home/chat/friend"
        }, res => {
            // console.log("我的朋友", res)
            // var friendList=res.data.friend
            // console.log("朋友列表",friendList[friendList.length-1])
            getApp().globalData.friendList = res.data.friend
            getApp().globalData.myInfo = res.data.mine
            // this.setData({
            // 	friendList:friendList,
            // 	myInfo:res.data.mine,
            // 	friendContentList:friendList[friendList.length-1].list
            // })
            // this.webSocket()
        })
    },

    webSocket() {
        // 创建Socket

        var that = this;
        getApp().globalData.SocketTask.onOpen(res => {
            // socketOpen = true;
            // console.log('监听 WebSocket 连接打开事件。', res)
        })
        getApp().globalData.SocketTask.onClose(onClose => {
            console.log('监听 WebSocket 连接关闭事件。', onClose)
            socketOpen = false;
        })
        getApp().globalData.SocketTask.onError(onError => {
            // console.log('监听 WebSocket 错误。错误信息', onError)
            // socketOpen = false
        })
        getApp().globalData.SocketTask.onMessage(onMessage => {
            // console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息index', (JSON.parse(onMessage.data)))
            var msg = JSON.parse(onMessage.data)
            if (msg.type == 'ping') {
                var heartbeat = {
                    type: 'pong',
                    content: '心跳检测'
                }
                getApp().globalData.SocketTask.send({
                    data: JSON.stringify(heartbeat),
                    success: function (res) {
                        // console.log('发送成功', res)
                    },
                    fail: function (err) {
                        // console.log("发送失败", err)
                        that.webSocket()

                    },
                })
            } else if (msg.type == 'msg_count') {
                var friendList = this.data.friendList
                for (var i = 0; i < friendList.length; i++) {
                    for (var x = 0; x < friendList[i].list.length; x++) {
                        if (friendList[i].list[x].id == msg.id) {
                            friendList[i].list[x].msg_count = msg.msg_count
                        }
                    }
                }
                // console.log("未读数量", friendList)
                this.setData({
                    friendList: friendList
                })
            }
        })
    },
    /**
     * 请求轮播图
     */
    req_banner() {
        //请求轮播图
        this.request({
            url: this.data.host + '/home/index/banner?from=warehouse&wh_id=' + this.data.wh_id
        }, this.get_banner_ok, null, res => {
            this.req_cat_data(this.data.catIndex)

            //请求供应商
            // this.req_shops();

            this.getSpecialList(); //天天特价或秒杀
            this.getvideoList(); //视频商品
            this.getSeckillList(); //秒杀
            // this.getNewSort() //查询分类

            this.getTime()
            this.getRate()

        }); //(队列请求)请求轮播图之后，接着请求产品

    },
    /**请求分类产品数据 */
    req_cat_data(catIndex) {
        let cat = this.data.catArr[catIndex];
        if (cat.current_page == cat.pages) {
            return;
        }
        cat.loading = true;
        this.setData({
            catArr: this.data.catArr
        })
        this.request({
            url: this.data.host + cat.url,
            data: {
                ...cat.reqData,
                //  limit:1,
                page: (cat.current_page * 1) + 1,
                wh_id: this.data.wh_id,
                limit: 20,
            }
        }, res => {
            this.get_pdcs_ok(catIndex, res);
        }, null, res => {
            let cat = this.data.catArr[catIndex];
            cat.loading = false;
            this.setData({
                catArr: this.data.catArr
            })


        });
    },
    //请求天天特价产品数据

    getSpecialList(index) {
        let special = this.data.special[this.data.specialIndex];
        this.request({
            url: this.data.host + special.url,
            data: {
                limit: 20,
                page: 1,
                wh_id: this.data.wh_id,
                ...special.data
            }
        }, res => {
            // console.log("天天特价", res)
            var list = res.data
            if (this.data.specialIndex == 1) {
                list.map(val => {
                    val.sku = val.total_num - val.sales
                    val.thumb = this.get_thumb(val.product_img);
                })
            } else {
                list.map(val => {
                    val.thumb = this.get_thumb(val.product_img);
                })
            }

            this.setData({
                specialloading: false,
                specialList: list
            })
        });
    },
    //请求整点秒杀
    getSeckillList(index) {
        // let special = this.data.special[this.data.specialIndex];
        this.request({
            url: this.data.host + "/home/supplier/product/index",
            data: {
                limit: 20,
                page: 1,
                wh_id: this.data.wh_id,
                is_seckill: 1
            }
        }, res => {
            // console.log("整点秒杀", res)
            var list = res.data
            list.map(val => {
                // val.sku = val.total_num - val.sales
                val.thumb = this.get_thumb(val.product_img);
            })

            this.setData({
                seckillloading: false,
                seckillList: list
            })
        });
    },
    //视频商品列表
    getvideoList(index) {
        // let special = this.data.special[this.data.specialIndex];
        this.request({
            url: this.data.host + "/home/supplier/product/index",
            data: {
                limit: 20,
                page: 1,
                wh_id: this.data.wh_id,
                is_video: 1
            }
        }, res => {
            // console.log("整点秒杀", res)
            var list = res.data
            list.map(val => {
                // val.sku = val.total_num - val.sales
                val.thumb = this.get_thumb(val.product_img);
            })

            this.setData({
                videoloading: false,
                videoList: list
            })
        });
    },
    to_detail() {
        wx.navigateTo({
            url: '/pages/goodsDetail/goodsDetail'
        })
    },
    catchPdc() {
        // console.log("catch")
    },


    /**请求商家top版this.req_brandPdcs */
    req_shops() {

        this.request({
            url: this.data.host + '/home/supplier/index?wh_id=' + this.data.wh_id + "&limit=12",
        }, this.get_shop_ok);
    },
    req_brandPdcs() {
        this.request({
            url: this.data.host + '/home/supplier/product/index?order=is_new&wh_id=' + this.data.wh_id
        }, res => {
            // console.log("/home/supplier/index?order=is_new&wh_id=", res);
            res.data.map(val => {
                val.thumb = this.get_thumb(val.product_img)
            })
            this.setData({
                brandPdcs: res.data
            })
        });
    },

    get_shop_ok(res) {
        // console.log("供应商列表", res);
        res.data.map(val => {
            val.thumb = this.get_thumb(val.logo)
            val.product_list.map(pdc => {
                pdc.pdcImg = this.get_thumb(pdc.product_img)
            })
        })
        this.setData({
            supplierArr: res.data
        })
    },
    stop() {},
    toStore(e) {
        // console.log(e)
        var store = e.currentTarget.dataset.store
        wx.navigateTo({
            url: '/pages/store/storeInfo/storeInfo?supplier_id=' + store.supplier_id
        })
    },
    toGoods(e) {
        var pdc = e.currentTarget.dataset.pdc
        wx.navigateTo({
            url: '/pages/goodsDetail/goodsDetail?pid=' + pdc.pid + "&supplier_id=" + pdc.supplier_id
        })
    },
    toTop() {
        wx.navigateTo({
            url: '/pages/cls/index/topStore/topStore'
        })
    },
    /**
     *  @param {int} catIndex 选中的分类索引
     * @param {*} res 后台返回的产品数据
     */
    get_pdcs_ok(catIndex, res) {
        let catArr = this.data.catArr;
        let cat = catArr[catIndex];
        cat.pages = res.pages;
        cat.current_page = res.current_page;
        // console.log("刷新底部产品列表", res);
        // console.log("选中的分类索引", catIndex);
        if (catIndex == 1) {
            res.data.map(val => {
                val.sku = val.total_num - val.sales
                val.thumb = this.get_thumb(val.product_img);
            })
        } else {
            res.data.map(val => {
                val.thumb = this.get_thumb(val.product_img);
                // console.log("val.thumb",val.thumb);
            });
        }

        res.current_page == 1 ? cat.data = res.data : cat.data = cat.data.concat(res.data);
        this.setData({
            catArr,
        });
        wx.stopPullDownRefresh({
            success: (res) => {},
        })
        // this.setData({
        //   pdcArr: res.data
        // })
    },
    // 渲染头条数据

    //渲染轮播图数据
    get_banner_ok(res) {
        res.data.map(val => {
            val.thumb = this.get_thumb(val.photo, 'wide');
            // console.log("val.thumb",val.thumb);
            val.color = val.color ? val.color : '#2EB356'
        })
        this.setData({
            bannerArr: res.data,

        })
        //请求通告
        this.req_declare();
    },
    req_declare() {
        this.request({
            url: this.data.host + '/home/index/declare?from=warehouse&wh_id=' + this.data.wh_id
        }, res => {
            // console.log("declare", res);
            this.setData({
                declareArr: res.data
            })
        });
    },
    article_click(e) {
        //+
        let that = this;
        wx.navigateTo({
            url: '../../article/Index?content=1',
            success: function (obj) {
                //传递产品数据
                obj.eventChannel.emit('content', that.data.declareArr[e.currentTarget.dataset.index]
                    .content)
            }
        })
    },

    /**
     * 收藏点击
     */
    collect_click(e) {
        // console.log("collect_click", e);
        let pdc = e.detail;
        let index = e.currentTarget.dataset.index;
        let status = pdc.collected ? 0 : 1;
        this.request({
            url: this.data.host + '/home/user/collect/collect',
            data: {
                status: status,
                can_id: pdc.pid,
                type: 1
            },
            method: 'post'
        }, res => {
            // console.log("collect_ok", res);

            let item = this.data.catArr[this.data.catIndex].data[index];
            item.collected = status;
            item.collects = status ? (item.collects * 1) + 1 : item.collects - 1;
            this.setData({
                catArr: this.data.catArr
            })
        });
    },
    sortcollect_click(e) {
        let pdc = e.detail;
        let index = e.currentTarget.dataset.index;
        let status = pdc.collected ? 0 : 1;
        this.request({
            url: this.data.host + '/home/user/collect/collect',
            data: {
                status: status,
                can_id: pdc.pid,
                type: 1
            },
            method: 'post'
        }, res => {
            // console.log("collect_ok", res);

            let item = this.data.sortFlowerList;
            item[index].collected = status;
            item[index].collects = status ? (item[index].collects * 1) + 1 : item[index].collects - 1;
            this.setData({
                sortFlowerList: item
            })
        });
    },
    toDetail(e) {
        // console.log(e)
        var pdc = e.detail
        var from = "seckill"
        wx.navigateTo({
            url: '/pages/goodsDetail/goodsDetail?pid=' + pdc.pid + "&supplier_id=" + pdc.supplier_id + "&from=" + from
        })
    },

    /**
     * 添加购物车按钮点击事件
     * @param {*} param0 
     */
    add_cart_click(e) {
        let pdc = e.detail;
        // console.log("秒杀", pdc)
        this.setData({
            nums: 1,
            addCart: true,
            pdc: pdc,
            sku: pdc.sku,
            product_id: pdc.pid,
            product_name: pdc.product_name,
            carTitle: e.currentTarget.dataset.titlt

        });
    },
    add_cart_click2(e) {
        let pdc = e.detail;
        this.setData({
            nums: 1,
            addCart: true,
            pdc: pdc,
            sku: pdc.sku,
            product_id: pdc.pid,
            product_name: pdc.product_name,
            carTitle: "整点秒杀"

        });
    },
    onCloseCart() {
        this.setData({
            addCart: false
        })
    },
    /**
     * 添加产品到购物车
     */
    add_cart() {
        // console.log("add_cart", this.data.nums, this.data.product_id);
        // if (this.data.carTitle == "整点秒杀") {
        // 	this.request({
        // 		url: this.data.host + '/home/ump/seckill/preinfo',
        // 		data: {
        // 			seckill_id: this.data.pdc.seckill_id,
        // 			nums: this.data.nums,
        // 			wh_id: getApp().globalData.warehouse.wh_id
        // 		},
        // 		method: 'GET'
        // 	}, this.add_preinfo_ok);
        // } else {



        // }
        let data = {
            pid: this.data.product_id,
            nums: this.data.nums,
        }
        let pdc = this.data.pdc
        if (pdc.is_seckill == 1 && this.data.carTitle == "整点秒杀") { //秒杀
            data.from = "seckill"
        } else {
            data.from = "flower"
        }

        this.request({
            url: this.data.host + '/home/cart/addToCart',
            data: data,
            method: 'post'
        }, this.add_cart_ok);

    },
    //立即购买
    buy_good() {
        console.log("立即购买", this.data.pdc)
        let data = {
            pid: this.data.product_id,
            nums: this.data.nums,
            wh_id: this.data.wh_id
        }
        let pdc = this.data.pdc
        if (pdc.is_seckill == 1 && this.data.carTitle == "整点秒杀") { //秒杀
            data.from = "seckill"
        } else {
            data.from = "flower"
        }

        this.request({
            url: this.data.host + '/home/flower/preInfo',
            data: data,
            method: 'get'
        }, res => {
            this.setData({
                addCart: false
            })
            res.data.cashier_decca = this.get_thumb(res.cashier_decca, 'wide');
            let that = this;
            wx.navigateTo({
                // url: '/pages/order_confirm/order_confirm',
                url: '/pages/neworder_confirm/order_confirm',
                success: function (obj) {
                    // 通过eventChannel向被打开页面传送数据

                    obj.eventChannel.emit('orderData', {
                        wh_id: that.data.wh_id,
                        // index: that.data.areaData[that.data.tabIndex].index,
                        data: res.data,
                        m_addr: res.m_addr,
                        activeCar: data.from,
                        wuliu: res.data.freight_list,
                        specialList: res.data.extra_list,
                        pack_list: res.data.pack_list,
                        buyType: 1, //1立即购买0购物车
                        order_pei_type: res.order_pei_type,
                        orderWarehouse: res.warehouse
                    })
                }
            })
        });
    },

    /**
     * 添加购物车结果处理
     * @param {*} res  后台返回的数据
     */
    add_cart_ok(res) {
        // console.log("add_cart_ok",res);
        // this.setData({nums:1})
        this.setData({
            addCart: false
        })
        wx.showToast({
            title: res.msg,
            icon: 'success'
        })
    },
    add_preinfo_ok(res) {
        // console.log('add_preinfo_ok', res);
        wx.navigateTo({
            url: '/pages/preSaleList/preinfo/Order?noShowNum=1',
            success: function (obj) {
                // 通过eventChannel向被打开页面传送数据
                obj.eventChannel.emit('orderData', {
                    data: res.data,
                    m_addr: res.data.m_addr
                })
            }
        })
    },
    nums_change(e) {
        // this.data.nums = e.detail;
        this.setData({
            nums: e.detail
        })
        // console.log("nums_change", e)
    },

    area_change(e) {
        // let detail = e.detail;
        // console.log("area_change",e);
        let index = e.currentTarget.dataset.index;
        getApp().globalData.warehouse = this.data.areaData[index];

        this.setData({ //切换仓库，刷新产品数据
            swiperCurrent: 0,
            sortIndex: 0,
            wh_id: this.data.areaData[index].wh_id,
            warehouse: this.data.areaData[index]
        })
        this.getSpecialList();
        this.getvideoList()
        this.getSeckillList();
        this.data.catArr.map(val => { //初始化页码
            val.current_page = 0;
        });
        //请求轮播图
        this.request({
            url: this.data.host + '/home/index/banner?from=warehouse&wh_id=' + this.data.wh_id
        }, this.get_banner_ok, null, this.req_cat_data(this.data.catIndex)); //(队列请求)请求轮播图之后，接着请求产品
        //请求供应商
        // this.req_shops();
        //请求时间
        this.getTime();
        //查询分类
        // this.getNewSort()
        //查询涨跌
        this.getRate()
        //查询实时成交、今日销量
        this.getSales()


    },
    /**
     * 交易大厅点击事件
     */
    morning_click() {
        wx.navigateTo({
            url: '/pages/cls/theme/Index?title=预售专区&type=6&wh_id=' + this.data.wh_id,
        })
    },
    /**斗南专区 */
    dounan_click() {
        // console.log("this.data.wh_id",this.data.wh_id)
        wx.navigateTo({
            url: '/pages/cls/theme/Index?title=扫底专区&wh_id=4',
        })
    },
    /**扫底专区 */
    sweep_click() {
        wx.navigateTo({
            url: '/pages/cls/list/BaseList?title=斗南专享&reqUrl=/home/supplier/product/index',
        })
    },
    /**秒杀专区 */
    seckill_click() {
        // wx.navigateTo({
        //   url: '/pages/cls/theme/Index?title=秒杀专区&type=5&wh_id=' + this.data.wh_id,
        // })
        var title = "秒杀专区"
        // if (this.data.wh_id != 1 && this.data.wh_id != 4) {
        //     title = "捡漏"
        // }
        wx.navigateTo({
            // url: '/pages/cls/list/BaseList?reqUrl=/home/ump/seckill/product&preUrl=/home/ump/seckill/preinfo&title=秒杀专区',
            url: '/pages/cls/list/BaseList?reqUrl=/home/supplier/product/index&preUrl=/home/ump/seckill/preinfo&title=' + title,
        })
    },
    // 次日达
    toNextDay() {
        wx.navigateTo({
            url: '/pages/cls/list/BaseList?reqUrl=/home/supplier/product/index&preUrl=/home/ump/seckill/preinfo&title=次日达',
        })
    },
    //跨区域
    toRegion() {
        wx.navigateTo({
            url: '/pages/cls/list/BaseList?reqUrl=/home/supplier/product/index&preUrl=/home/ump/seckill/preinfo&title=跨区域',
        })
    },
    /**直播专区 */
    live_click() {
        var title = "市场捡漏"
        if (this.data.wh_id != 1 && this.data.wh_id != 4) {
            title = "捡漏"
        }
        wx.navigateTo({
            url: '/pages/cls/list/BaseList?reqUrl=/home/supplier/product/index&preUrl=/home/ump/seckill/preinfo&title=' + title,
        })
    },
    clickToLive() {
        wx.navigateToMiniProgram({
            appId: 'wx5076326205f63fa6',
            path: '/page/home/home_index/home_index',
            extraData: {
                foo: 'bar'
            },
            envVersion: 'release',
            success(res) {
                // 打开成功
            }
        })
    },
    /**鲜花预售 */
    presell_click() {
        wx.navigateTo({
            url: '/pages/preSaleList/preSaleList?wh_id=' + this.data.wh_id,
        })
        // wx.navigateTo({
        // 	url: '/pages/cls/list/BaseList?reqUrl=/home/ump/presell/product&preUrl=/home/ump/presell/preinfo&title=预售专区',
        // })
    },
    /**精品花束 */
    pdcs_click() {
        wx.navigateTo({
            url: '/pages/cls/pdcList/Index?cate_id=17',
        })
    },
    /**跳转商家主页 */
    supplier_click(e) {
        // console.log("supplier_click", e);
        let supplier = e.currentTarget.dataset.supplier;
        wx.navigateTo({
            url: '/pages/cls/pdcList/Index?supplier_id=' + supplier.supplier_id + "&title=" + supplier
                .title,
        })
    },
    brand_click(e) {
        // console.log("brand_click", e);
        let pdc = e.currentTarget.dataset.pdc || {
            pid: 0
        };
        wx.navigateTo({
            url: '/pages/cls/pdcList/Index?pid=' + pdc.pid,
        })
    },
    /**确认搜索内容 */
    search_click(e) {
        // console.log("search_click", e);
        wx.navigateTo({
            url: '/pages/cls/pdcList/Index?so=' + e.detail
        })

    },

    /**
     * 显示商家基地视频
     * @param {event} e 
     */
    show_video(e) {

        this.setData({
            showVideo: this.data.imgHost + '/' + e.detail
        })
    },
    onShareAppMessage(res) {
        // console.log("onShareAppMessage", res);
        let path = "/pages/cls/index/index?uid=" + getApp().globalData.userInfo.uid;
        let title = "";
        if (res && res.target) {
            let pid = res.target.dataset.pid;
            let product_id = res.target.dataset.product_id;
            if (pid) {
                path = '/pages/cls/pdcList/Index?pid=' + pid + '&product_id=' + product_id + '&uid=' + getApp()
                    .globalData.userInfo.uid;
                title = "您的朋友向你推荐了一款鲜花"
            }
        }



        // const promise = new Promise(resolve => {
        //   setTimeout(() => {
        //     resolve({
        //       title: '自定义转发标题'
        //     })
        //   }, 2000)
        // })
        return {
            title: title,
            path: path,
            // promise 
        }
    },
    //跳转详情
    to_detail() {
        // console.log("跳转详情")
        wx.navigateTo({
            url: '/pages/goodsDetail/goodsDetail'
        })
    },
    //查看更多
    toList(e) {
        // console.log("跳转更多", e)
        var url = '/pages/cls/index/goodsList/goodsList?type=' + e.currentTarget.dataset.type + "&wh_id=" +
            this.data.wh_id + "&title=" + e.currentTarget.dataset.title
        if (e.currentTarget.dataset.type == 3) { //分类
            url = '/pages/cls/index/goodsList/goodsList?type=' + e.currentTarget.dataset.type + "&cate_id=" +
                this.data.sortList[this.data.sortIndex].cate_id + "&wh_id=" + this.data.wh_id + "&title=" + this.data.sortList[this.data.sortIndex].title
        } else {
            url = '/pages/cls/index/goodsList/goodsList?type=' + e.currentTarget.dataset.type + "&wh_id=" +
                this.data.wh_id + "&title=" + e.currentTarget.dataset.title
        }
        wx.navigateTo({
            url: url
        })
    },
    //获取商品涨跌
    getRate() {
        this.request({
            url: this.data.host + '/home/index/rateByCate',
            data: {
                wh_id: this.data.wh_id,
            },
            method: 'GET'
        }, res => {
            var list = res.data
            list.map(val => {
                if (val.change_rate > 0) {
                    val.state = 1
                } else {
                    val.state = 0
                }
            })
            this.setData({
                analysisList: list
            })

        });
    },
    //获取实时成交量
    getSales() {
        this.request({
            url: this.data.host + '/home/index/sales',
            data: {
                wh_id: getApp().globalData.warehouse.wh_id
            },
            method: 'GET'
        }, res => {

            this.setData({
                turnoverList: res.data.real_list,
                sales: res.data.sales
            })
        });
    },
    onSaledetail(e) {
        var pdc = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/pages/goodsDetail/goodsDetail?pid=' + pdc.pid + "&supplier_id=" + pdc.supplier_id + "&from=" + pdc.from
        })
    },
    //跳转分仓拼单
    clickToCollate() {
        wx.navigateTo({
            url: '/pages/collate/collate?warehouse=' + JSON.stringify(this.data.warehouse),
        })
    },
    //添加同城群
    addCityGroup() {
        this.setData({
            showGroup: false
        })
        wx.navigateTo({
            url: '/pages/region/whInfo/index',
        })
    },
    changeActive(e) {
        var index = e.currentTarget.dataset.index
        // if(index==3){
        //     wx.showToast({
        //       title: '开发中···',
        //       icon:"none"
        //     })
        //     return;
        // }
        this.setData({
            activeIndex: index
        })
    },



})